<template>
  <el-dialog :visible.sync="dialogFormVisible"  title="订餐申请"  width="800px"  @close="closeDialog" >
    <!-- 右上角功能按钮区域 -->
    <div class="top-right-buttons" style="position: absolute; top: 60px; right: 20px; z-index: 1000;">
      <el-button type="primary" v-if="canEditMeal" @click="saveOrder">保存</el-button>
      <el-button type="primary"  v-if="canEditMeal" @click="handleOrder">提交</el-button>
    </div>
    
    <!-- 餐品信息表格 -->
    <div style="margin-bottom: 20px; margin-top: 60px;">
      <h3>餐品信息</h3>
      <el-table :data="mealorderList" border  style="width: 100%">
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="餐品种类" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.mid" placeholder="选择餐品" style="width: 100%" :disabled="!canEditMeal"  @change="handleMealChange(scope.row)">
              <el-option v-for="meal in mealList" :key="meal.mid" :label="meal.mname" :value="meal.mid"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="订餐人员" align="center">
          <template slot-scope="scope">
            <el-button   
              type="text"   
              @click="showPersonSelect(scope.$index)"  
              :disabled="!canEditMeal" 
            >
              {{ getPersonDisplayText(scope.row) }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="订餐数量" width="100" align="center">
          <template slot-scope="scope">
            <el-input-number  
              v-model="scope.row.num"  
              :disabled="!canEditMeal"  
              controls-position="right" 
              @change="calculateTotal(scope.row)"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="订餐单价" width="100" align="center">
          <template slot-scope="scope">
            <span>¥{{ scope.row.price || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订餐总价" width="100" align="center">
          <template slot-scope="scope">
            <span>¥{{ (scope.row.price * scope.row.num) || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" v-if="canEditMeal">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              size="mini" 
              icon="el-icon-plus" 
              @click="addMealRow"
              circle
            ></el-button>
            <el-button 
              type="danger" 
              size="mini" 
              icon="el-icon-minus" 
              @click="removeMealRow(scope.$index)"
              circle
              :disabled="mealorderList.length === 1"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      
    </div>

    <!-- 订餐信息 -->
    <div style="margin-bottom: 20px;">
      <h3>订餐信息</h3>
      <el-form :model="form"  label-width="100px">
        <el-form-item label="费用项目">
          <el-button   type="text"    @click="showProjectSelect"  :disabled="!canEditMeal"
            style="width: 100%; text-align: left; border: 1px solid #DCDFE6; padding: 8px 15px; border-radius: 4px;"
          >
            {{ displayInfo.pname || '选择费用项目' }}
          </el-button>
        </el-form-item>
        
        <el-form-item label="费用部门">
          <el-input v-model="displayInfo.dname" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="订餐类型">
          <el-radio-group v-model="form.ordertype" :disabled="!canEditMeal">
            <el-radio :label="0">午餐</el-radio>
            <el-radio :label="1">晚餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="申请编号">
          <el-input v-model="form.orderid" disabled></el-input>
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="displayInfo.ename" disabled></el-input>
        </el-form-item> 
        <el-form-item label="申请时间">
          <el-input v-model="form.ordertime" disabled></el-input>
        </el-form-item> 
        <el-form-item label="订餐人员">
          <el-input v-model="form.orderpersons" disabled placeholder="自动汇总所有餐品的订餐人员"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input   type="textarea"  v-model="form.remark"  :rows="2"  :disabled="!canEditMeal"  placeholder="请输入备注信息"  ></el-input>
        </el-form-item>
        <el-form-item label="订餐凭证" prop="orderpictureurl">
        <el-upload  class="upload"  action="#"  list-type="picture-card" :show-file-list="false" :before-upload="beforeUpload"
         :http-request="handleUpload" :on-success="handleSuccess" :on-remove="handleRemove" :disabled="!canEditMeal">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
        

      </el-form>
    </div>
    <!-- 部门审核 -->
    <div style="margin-bottom: 20px;">
      <el-form :model="form" label-width="100px">
        <el-form-item label="部门审核">
          <el-input   v-model="form.deptAudit"   :disabled="!canEditDeptAudit"  placeholder="请输入审核意见"  ></el-input>
        </el-form-item>  
        <el-form-item label="公司审核">
          <el-input    v-model="form.companyAudit"   :disabled="!canEditCompanyAudit"  placeholder="请输入审核意见"   ></el-input>
        </el-form-item>
      </el-form>
    </div>
    
    <div slot="footer" style="text-align: right; padding: 10px 0;">
      <el-button   v-if="showRejectButton"  @click="handleReject"   style="margin-right: 10px;" >
        驳回
      </el-button>
      <el-button   v-if="showSubmitButton"  type="primary"   @click="handleApprove">
        提交
      </el-button>
    </div>
    
    <person-select 
      :visible="personSelectVisible"  
      :deptno="deptno"  
      :selected-persons="currentSelectedPersons"  
      @confirm="confirmPersonSelect"  
      @close="personSelectVisible = false"
></person-select>
    <project-select 
    :visible="projectSelectVisible" 
    :deptno="deptno"  
    :dname="dname"  
    :selected-project="tempProjectId"  
    @confirm="confirmProjectSelect"  
    @close="projectSelectVisible = false">
    </project-select>
  </el-dialog>
</template>

<script>
import PersonSelect from './PersonSelect.vue';
import ProjectSelect from './ProjectSelect.vue';

export default {
  name: 'OrderDetail',
  components: {
    PersonSelect,
    ProjectSelect
  },
  props: {
    visible: Boolean,
    orderInfo:Object,
    userInfo:Object
  },
  data() {
    return {
      pid:'',
      mealList: [],
      dialogFormVisible: false,
      imageUrl:'',
      deptno:this.userInfo.deptno || '',
      dname:this.userInfo.dname || '',  
      mealorderList: [
        {
          mid: '',
          mname: '',
          orderpersons: '',
          num: 0,
          price: 0
        }
      ],
      querypidForm:{
        empno:this.userInfo.empno,
        ordertime:new Date().toISOString().split('T')[0]
      },
      form: {
        id:0,
        orderid:'',
        pid: 0,
        deptno: this.userInfo.deptno || '',
        empno: this.userInfo.empno,
        ordertype: 0,
        num:0,
        orderpersons: '',
        amount: 0,
        ordertime: new Date().toISOString().split('T')[0],
        remark: '',
        deptAudit: '',
        companyAudit: '',
        orderpictureurl:''
        
      },
      displayInfo: {
        pname: '',
        dname: this.userInfo.dname || '',
        ename: this.userInfo.ename
      },
      personSelectVisible: false,
      projectSelectVisible: false,
      currentMealIndex: -1,
      currentSelectedPersons: [],
      tempProjectId: 0
    }
  },
  computed: {
    canEditMeal() {
      return this.userInfo.roleid.includes(4)
    },
    canEditDeptAudit() {
      return this.userInfo.roleid.includes(3)
    },
    canEditCompanyAudit() {
      return this.userInfo.roleid.includes(2)
    },
    showSubmitButton() {
      return this.userInfo.roleid.includes(2) || this.userInfo.roleid.includes(3)
    },
    showRejectButton() {
      return this.userInfo.roleid.includes(2) || this.userInfo.roleid.includes(3)
    }
  },
  watch: {
    visible(val) {
      this.dialogFormVisible = val;
    },
    orderInfo: {
      handler(val) {
        //防止空对象传入,检测其是否为有效值，并且至少有一个对象
        if (val && Object.keys(val).length > 0) {
          
          this.form.id = val.orderInfo.id || 0;
          this.form.orderid = val.orderInfo.orderid;
          this.form.pid = val.orderInfo.pid;
          this.form.ordertype = val.orderInfo.ordertype;
          this.form.remark = val.orderInfo.remark;
          this.form.num = val.orderInfo.num;
          this.form.amount = val.orderInfo.amount;
          this.form.ordertime = val.orderInfo.ordertime;
          this.form.deptAudit = val.orderInfo.deptAudit;
          this.form.companyAudit = val.orderInfo.companyAudit;
          this.form.orderpictureurl = val.orderInfo.orderpictureurl;
          this.imageUrl = val.orderInfo.orderpictureurl;
          
          this.displayInfo.pname = val.orderInfo && val.orderInfo.pname ? val.orderInfo.pname : '';
          this.displayInfo.dname = val.orderInfo && val.orderInfo.dname ? val.orderInfo.dname : this.userInfo.dname;
          this.displayInfo.ename = val.orderInfo && val.orderInfo.ename ? val.orderInfo.ename : this.userInfo.ename;
          
          if (val.mealOrderList && val.mealOrderList.length > 0) {
            //若有数据传输过来则填充回显在表单上
            this.mealorderList = val.mealOrderList.map(item => ({
              id: item.id || 0,
              mid: item.mid || '',
              mname: item.mname || '',
              orderpersons: item.orderpersons || '',
              num: item.num || 0,
              price: item.price || 0
            }));
          } else {
            this.mealorderList = [{ 
              mid: '', 
              mname: '', 
              orderpersons: '', 
              num: 0, 
              price: 0 
            }];
          }
          
          this.updateOrderSummary();
          //
          this.tempProjectId = val.orderInfo && val.orderInfo.pid ? val.orderInfo.pid : '';
        } else {
          this.getDefalutPid()
        }
      },
      immediate: true
    },
    userInfo(val) {
      //
      this.deptno = val && val.deptno ? val.deptno : '';
      this.dname = val && val.dname ? val.dname : '';
      this.form.empno = val && val.empno ? val.empno : '';
      this.form.deptno = val && val.deptno ? val.deptno : '';
      
      
    }

  },
  methods: {
    getDefalutPid(){
      this.$http.post("/getDefaultPid",this.querypidForm).then(res => {
        this.form.pid = res.data.pid
        this.displayInfo.pname = res.data.pname
      })
    },
    addMealRow() {
      this.mealorderList.push({
        mid: '',
        mname: '',
        orderpersons: '',
        num: 0,
        price: 0
      });
    },
    
    removeMealRow(index) {
      if (this.mealorderList.length === 1) {
        this.$message.warning('至少保留一个餐品');
        return;
      }
      this.mealorderList.splice(index, 1);
      this.updateOrderSummary();
    },
    
    getPersonDisplayText(row) {
      if (row.orderpersons && row.orderpersons.length > 0) {
        return row.orderpersons;
      }
      return '请选择人员';
    },

        createOrderId() {
          let now = new Date();
          let year = now.getFullYear();
          let month = String(now.getMonth() + 1).padStart(2, '0');
          let day = String(now.getDate()).padStart(2, '0');
          let hour = String(now.getHours()).padStart(2, '0');
          let minute = String(now.getMinutes()).padStart(2, '0');
          let second = String(now.getSeconds()).padStart(2, '0');
          
          return 'EMP' + this.userInfo.empno + '_' + year + month + day + hour + minute + second;
      },

    updateOrderSummary() {
      let allPersons = new Set();//自动去重
      this.mealorderList.forEach(meal => {
        if (meal.orderpersons) {
          //去掉空格，过滤掉空字符串
         let persons = meal.orderpersons.split(',').map(p => p.trim()).filter(p => p);
          persons.forEach(person => allPersons.add(person));
        }
      });
      
      this.form.orderpersons = Array.from(allPersons).join(', ');
      this.form.num = this.mealorderList.reduce((total, meal) => total + (meal.num || 0), 0);
      this.form.amount = this.mealorderList.reduce((total, meal) => total + ((meal.price || 0) * (meal.num || 0)), 0);
    },

    closeDialog() {
      this.form = {
        id: 0,
        orderid: '',
        pid: '',
        deptno: this.userInfo && this.userInfo.deptno ? this.userInfo.deptno : '',
        empno: this.userInfo && this.userInfo.empno ? this.userInfo.empno : '',
        ordertype: 0,
        num: 0,
        orderpersons: '', 
        amount: 0,
        ordertime: new Date().toISOString().split('T')[0],
        remark: '',
        deptAudit: '',        
        companyAudit: '',
        orderpictureurl: ''      
      };
      this.displayInfo = {
        pname: '',
        dname: this.userInfo.dname || '',
        ename: this.userInfo.ename || ''
      };
      this.mealorderList = [
        { mid: '', mname: '', orderpersons: '', num: 0, price: 0 }
      ];
      this.imageUrl = '';
      this.currentMealIndex = -1;
      this.tempProjectId = '';
      this.$emit('close');
    },

    handleApprove() {
      this.submitReview('approve')
    },

    handleReject() {
      this.submitReview('reject')
    },  

    submitReview(type) {
      let params = {
        orderid: this.form.orderid,
        rolename: this.userInfo.roleid.includes(2) ? 'prosident' : 'manager',
        type: type,
        deptAudit: this.form.deptAudit,
        companyAudit: this.form.companyAudit
      }
  
      this.$http.post('/revieworder', params).then(res => {
        if (res.data.msg === 'success') {
          this.$message.success(res.data.reason || '操作成功')
          this.$emit('refresh-list')
          this.closeDialog()
        } else {
          this.$message.error(res.data.reason || '操作失败')
        }
      }).catch(error => {
        console.error('审核操作失败:', error)
        this.$message.error('审核操作失败')
      })
    },

    handleMealChange(mealRow) {
      //去餐品表寻早对应餐品以便更新相关信息
      let selectedMeal = this.mealList.find(meal => meal.mid === mealRow.mid)
      if (selectedMeal) {
        mealRow.price = selectedMeal.price
        mealRow.mname = selectedMeal.mname
      }
      this.updateOrderSummary();
    },

    calculateTotal(mealRow) {
      this.updateOrderSummary();
      return (mealRow.price || 0) * (mealRow.num || 0);
    },

    confirmPersonSelect(selectedPersonNames) {
        if (this.currentMealIndex === -1) return;
        const allSelectedPersons = new Set();
        this.mealorderList.forEach((meal, index) => {
          if (index !== this.currentMealIndex && meal.orderpersons) {
            let persons = meal.orderpersons.split(',').map(p => p.trim()).filter(p => p);
            persons.forEach(person => allSelectedPersons.add(person));
          }
        });
        
          let duplicatePersons = selectedPersonNames.filter(name => allSelectedPersons.has(name));
          if (duplicatePersons.length > 0) {
            this.$message.error('存在重复订餐人员：' + duplicatePersons.join(', '));
            return;
          }
          //添加同一日期同意类型的订餐验证
          if(selectedPersonNames.length > 0){
            let checkParams = {
              ordertime:this.form.ordertime,
              ordertype:this.form.ordertype,
              persons:selectedPersonNames
            }
            this.$http.post('/checkDuplicates',checkParams).then(res => {
              if(res.data.success && res.data.hasDuplicate){
                let validPersons = res.data.validPersons||[]
                this.$message.warning('以下人员已在' + (this.form.ordertype === 0 ? '午餐' : '晚餐') + '订餐中存在：' + res.data.duplicatePersons.join(', '));
                selectedPersonNames = validPersons;
               

              } else if (!res.data.success) {
                 this.$message.warning('人员验证失败，请确认后提交');
              }
              let currentMeal = this.mealorderList[this.currentMealIndex];
                currentMeal.orderpersons = selectedPersonNames.join(', ');
                currentMeal.num = selectedPersonNames.length;
                this.updateOrderSummary();
                this.personSelectVisible = false;
                this.currentMealIndex = -1;
            })

          }
          else {
    // 如果没有选择人员，直接关闭
            this.personSelectVisible = false;
            this.currentMealIndex = -1;
          }
       
    },
      showProjectSelect() {
        this.tempProjectId = this.form.pid
        this.projectSelectVisible = true
      },
    showPersonSelect(index) {
      this.currentMealIndex = index;
      let currentMeal = this.mealorderList[index];
      this.currentSelectedPersons = currentMeal.orderpersons 
        ? currentMeal.orderpersons.split(',').map(p => p.trim()).filter(p => p)
        : [];
      this.personSelectVisible = true;
    },

    confirmProjectSelect(selectedProject) {
      if (selectedProject) {
        this.form.pid = selectedProject.pid;
        this.displayInfo.pname = selectedProject.pname;
        this.tempProjectId = selectedProject.pid; 
      } else {
        if (this.tempProjectId) {
          this.form.pid = this.tempProjectId;
        }
      }
    },
    getMealList(){
      this.$http.get("/getOldMealList").then(res => {
        this.mealList = res.data
      })
    },
    saveOrder(){
     let validateResult = this.validateOrderForm();
      if (!validateResult.pass) {
        this.$message.error(validateResult.msg);
        return;
      }
      if(this.form.id == 0){
        this.form.orderid = this.createOrderId();
      }
      this.updateOrderSummary();
      let requestData = {
        orderInfo: this.form,
        mealOrderList: this.mealorderList
      };
      let url = '/addOrderInfo'
      if(this.form.id != 0){
        url = '/editOrderInfo'
      }
      this.$http.post(url, requestData).then(res => {
        if(res.data === 'success'){
          this.$emit('Ordersave', res.data)
        } else {
          this.$message.error("当前状态不可保存")
        }
      })
    },

    handleOrder(){
      let validateResult = this.validateOrderForm();
      if (!validateResult.pass) {
        this.$message.error(validateResult.msg);
        return;
      } else if(this.form.id == 0){
        this.form.orderid = this.createOrderId();
      }
      this.updateOrderSummary();
      let requestData = {
        orderInfo: this.form,
        mealOrderList: this.mealorderList
      };
      let url = '/addOrderInfo02'
      if(this.form.id != 0){
        url = '/editOrderInfo02'
      }
      this.$http.post(url, requestData).then(res => {
        if(res.data === 'success'){
          this.$emit('Ordersave', res.data)
        } else {
          this.$message.error("订单审核流程中，不能修改")
        }
      })
    },
    beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG || isPNG && isLt2M;
    },
        async handleUpload(config) {
          const file = config.file;
            if (this.form.orderpictureurl) { 
              try {
                await this.$http.post('/deleteOrderImage', { 
                  imageUrl: this.form.orderpictureurl
                });
                console.log('旧图片删除成功');
              } catch (err) {
                console.error('删除旧图片失败：', err);
                this.$message.warning('旧图片删除失败，但将继续上传新图片');
              }
            }
          let formData = new FormData();
          formData.append('file', file); 
          // 调用后端接口
          this.$http.post('/addPicture', formData, {
            headers: {
              'Content-Type': 'multipart/form-data' 
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.form.orderpictureurl = res.data.data; 
              config.onSuccess(res.data); 
              this.$message.success('图片上传成功');
            } else {
              config.onError(res.data); 
              this.$message.error('图片上传失败：' + res.data.msg);
            }
          }).catch(err => {
            config.onError(err);
            this.$message.error('上传失败：网络错误');
            console.error('上传错误：', err);
          });
        },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.form.orderpictureurl = ''; 
        this.imageUrl = ''; 
      }
    },
    handleSuccess(res, file) {
      this.imageUrl = this.form.orderpictureurl;
    },
    validateOrderForm() {
      for (let i = 0; i < this.mealorderList.length; i++) {
        let mealRow = this.mealorderList[i];
        if (mealRow.mid === '' || mealRow.mid === null || mealRow.mid === undefined) {
          return { pass: false, msg: '第' + (i + 1) + '行餐品：请选择餐品种类' };
        }
        if (!mealRow.orderpersons || mealRow.orderpersons.trim() === '') {
          return { pass: false, msg: `第${i+1}行餐品：请选择订餐人员` };
        }
      }
      if (!this.form.pid || this.form.pid === '' || this.form.pid === undefined) {
        return { pass: false, msg: '第' + (i + 1) + '行餐品：请选择订餐人员' };
      }
      

      let now = new Date(); 
      let hours = now.getHours(); 
      let minutes = now.getMinutes(); 
      let totalMinutes = hours * 60 + minutes; 
      if (this.form.ordertype === 0) {
        if (totalMinutes >= 920) { 
          return { pass: false, msg: '午餐订餐需在10:20之前提交' };
        }
      } 
      else if (this.form.ordertype === 1) {
        if (totalMinutes < 810 || totalMinutes > 980) { 
          return { pass: false, msg: '晚餐订餐需在13:30-16:20之间提交' };
        }
      }

      return { pass: true, msg: '验证通过' };
}

  },
  created(){
    this.getDefalutPid()
    this.getMealList()
    if (this.userInfo.deptno && !this.displayInfo.dname) {
    this.$http.get('/getDname/' + this.userInfo.deptno).then(res => {
      this.displayInfo.dname = res.data;
    })
  }
  }
}
</script>